#include <os/virmem.h>
#include <os/debug.h>
#include <os/driver.h>
#include <sys/ioctl.h>
#include <lib/string.h>
#include <lib/stddef.h>
#include <lib/stdio.h>
#include <driver/view/screen.h>

#ifndef DEVICE_NAME
#define DEVICE_NAME "video"
#endif

int ViewScreenOpen(view_screen_t *screen)
{
    int handle = DeviceOpen(DEVICE_NAME, 0);
    if (handle < 0)
        return -1;
    screen->handle = handle;
    return 0;
}

int ViewScreenClose(view_screen_t *screen)
{
    if (!screen)
        return -1;
    DeviceClose(screen->handle);
    screen->handle = -1;
    return 0;
}

int ViewScreenMap(view_screen_t *screen)
{
    if (screen->handle < 0)
        return -1;
    video_info_t video_info;
    // get video info
    int ret = DeviceDevCtl(screen->handle, VIDEOIO_GETINFO, &video_info);
    if (ret < 0)
        return -1;
    // get screen info
    screen->width = video_info.x_res;
    screen->height = video_info.y_res;
    screen->bit_per_pixel = video_info.bits_per_pixel;

    // count vram size
    uint32_t vramsize = video_info.x_res * video_info.y_res * screen->bit_per_pixel / 8;
    if (vramsize < 0)
        return -1;

    // map vram area
    uint8_t *vram = DeviceMMap(screen->handle, vramsize, IO_KERNEL);
    if (!vram)
        return -1;
    KPrint("[view]screen vram %x size %d w %d h %d bits %d\n",vram,vramsize,screen->width,screen->height,screen->bit_per_pixel);
    screen->vram = vram;
    return 0;
}

int ViewScreenUmmap(view_screen_t *screen)
{
    if (screen->handle < 0)
        return -1;
    if (!screen->vram)
        return -1;
    MemIoUnMap(screen->vram);
    return 0;
}
